import React, { Component } from 'react';
import { Tabs, List, Button,Table ,Divider,Modal ,Form,Input,Icon,Popover,InputNumber ,Switch,notification,Select,Cascader, Drawer,Row,Col ,Tag,Popconfirm ,Radio} from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../axios/api_lqy';
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
//弹出通知提醒框
function openNotification(type, message) {
    notification.open({
        type: type,
        message: message,
        duration: 2,
    });
};

class App extends Component {
	state = { 
		loading: false, //加载中...
		dataSource: [], 
		visible: false, //显示与隐藏
		modalData:'',//选中的数据
    handleType:0,//新增0 修改1
    topId:0,
 };
	componentDidMount() {
		this.fetch('');
	}
	//初始化加载数据
	fetch=(str)=>{
		this.setState({loading:true})
		APIService.selectDictionaryMaintenance(str).then(data=>{ //发送axios请求---字典查询
			const dataSource=data.data.data;
		            this.setState({
						dataSource:dataSource,
						loading:false,
					})
				 })
	}
	handleChangeTab = key => {
	
	};
	changeRadio=(e)=>{
		console.log(e.target.value)
		// this.setState({display: e.target.value==1 ? true : false})
	}
	//添加修改字典提交
    submitMenu=(e)=>{
		this.props.form.validateFields((err, values) => {
			if (!err) {
				if(this.state.handleType===0 ||this.state.handleType===3 ){
					values=Object.assign({}, values,{creatorId:parseInt(localStorage.getItem('userId')),parentId:this.state.modalData.id===undefined?null:this.state.modalData.id } )
				}else{
					values=Object.assign({}, values,{updaterId:parseInt(localStorage.getItem('userId')),parentId:this.state.modalData.parentId,id:this.state.modalData.id})
				}
        const that=this;
				APIService.addDictionaryMaintenance(values).then(data=>{
					if(data.data.code===200){
						openNotification('success', '操作成功')
					}else{
						openNotification('warning', data.data.msg)
					}
					that.handleCancel();
					that.props.form.resetFields();
				  that.fetch('');
				 })
				
			} else {
				console.log(err);
			}
		});
	}
   //弹出删除框
   showDeleteConfirm = (data) => {
	const that = this;
	confirm({
		title: '确认删除' + '[' + data.name + ']？',
		okText: '确认',
		okType: 'danger',
		cancelText: '取消',
		onOk() {
			if(data.children.length===0){
				APIService.deleteDictionaryMaintenance(data.id).then(data => {
					openNotification('success', '删除成功');
					that.fetch('');
				}).catch(function (error) {
					openNotification('error', error.message);
				});	
			}else{
				openNotification('warning', '权限有子权限');
			}
		},
		onCancel() {
			console.log('Cancel');
		},
	});
}

	onExpand=(record, index, indent, expanded)=>{
		
	}
	
    //0新增  1修改
	showModal = (data,type) => {
		const that=this;
		if(type===1){
			this.props.form.setFieldsValue({
				name: data.name,
				code:data.code,
				status:data.status
			})
		}
		this.setState({
			visible: true,
			modalData:data,
			handleType:type,
		  });
		
	  };
	  handleCancel = e => {
		this.props.form.resetFields();//清除form表单控件的值
		this.setState({
		  visible: false,
		});
	  };

	render() {
		const columns = [
      {
				dataIndex:'',
				width:'80px'
			},
			{
			  title: '字典编码',
			  dataIndex: 'code',
			},
			// {
			// 	title: '序号',
			// 	width: '10%',
			// 	render:(text,record,index)=> `${index+1}`,
			//   },
			{
			  title: '字典名称',
			  dataIndex: 'name',
			},
			{
			  title: '状态',
				dataIndex: 'status',
				render:(text,record)=>{
					// if(record.parentId){
						if(text===1){
							return <Tag color="magenta">停用</Tag>
						}else if(text==0){
							return <Tag color="green">启用</Tag>
						}
					// }else{
					// 	return <></>
					// }
					
				}
			},
			{
			  title: '创建时间',
			  dataIndex: 'createTime',
			},
			{
				title: '操作',
				width:'12%',
				render: (text, record) => {
					// if(record.status==0){
						return <span>
					  <a onClick={()=>this.showModal(record,3)}>添加</a>
					  <Divider type="vertical" />

					  <a  onClick={()=>this.showModal(record,1)}>修改</a>
					  {/* <Divider type="vertical" />
					  <a  onClick={()=>this.showDeleteConfirm(record)}>
						删除
					  </a> */}
					</span>
				}
					
		}
		  ];

		
		 const { getFieldDecorator } = this.props.form;
		 const formItemLayout = {
            labelCol: {
                xs: {
                    span: 30
                },
                sm: {
                    span: 10
                },
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                },
            },
        };
				//设置表单的排布--类栅格
		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
        };
        // 新增按钮
		var operations = <div className="mydiv" > <Button icon="plus" onClick={()=>this.showModal([],0)} type="primary" > 新增 </Button></div >
		return (
			<div className="shadow-radius">
				<Tabs tabBarExtraContent={operations} defaultActiveKey="1" onChange={this.handleChangeTab}>
					<TabPane tab="字典维护" key="1">
					<Table columns={columns} rowKey={(record)=>record.id}   dataSource={this.state.dataSource} pagination={false} loading={this.state.loading}   onExpand={(expanded,record)=>this.onExpand(expanded,record )}/>
					</TabPane>
					
				</Tabs>
				
				<Modal
				width='600px'
				title="新增/修改"
				visible={this.state.visible}
				centered
				onOk={this.submitMenu}
				onCancel={this.handleCancel}
				okText="保存"
				cancelText="取消"
				>
					<Form {...formItemLayout_addMenu}>
					<Form.Item label="字典编码">
						{getFieldDecorator('code', {
							rules: [{ required: true, message: '请填写字典编码！' }]
						})(<Input />)}
					</Form.Item>
					<Form.Item label="字典名称">
						{getFieldDecorator('name', {
							rules: [{ required: true, message: '请填写字典名称！' }]
						})(<Input />)}
					 </Form.Item>
					 {(this.state.modalData.parentId||this.state.handleType==3) ? <Form.Item label="状态">
						{getFieldDecorator('status', {
							rules: [{ required: true, message: '请选择状态！'}] ,initialValue:0
						})(<Radio.Group onChange={(e)=>{this.changeRadio(e)}}>
						<Radio value={0}>启用</Radio>
						<Radio value={1}>停用</Radio>
					</Radio.Group>)}
					</Form.Item> : ''}
          
				
				</Form>

				</Modal>
			

				
			</div>
		);
	}
}
export default Form.create()(App);